package com.hmall.search.listener;


import com.alibaba.fastjson.JSON;
import com.hmall.common.client.ItemClient;
import com.hmall.common.constants.MqConstants;
import com.hmall.common.pojo.Item;
import com.hmall.common.pojo.ItemDoc;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;

import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;


import javax.annotation.Resource;
import java.io.IOException;

@Component
public class MqListener {
    @Resource
    private RestHighLevelClient client;

    @Resource
    private ItemClient itemClient;

    /**
     * 上架消息接收
     *
     * @param id
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = MqConstants.HMALL_UP_QUEUE),
            //ExchangeTypes.TOPIC表示Exchange类型，默认是direct
            exchange = @Exchange(name = MqConstants.HMALL_EXCHANGE, type = ExchangeTypes.TOPIC),
            key = MqConstants.HMALL_UP_KEY
    ))
    public void upQueue(Long id) {
        System.out.println("消费者upQueue接收到消息：【" + id + "】");
        try {
            // 0.根据id查询商品数据
            Item item = itemClient.getItem(id);
            // 转换为文档类型
            ItemDoc itemDoc = new ItemDoc(item);

            // 1.准备Request对象
            IndexRequest request = new IndexRequest("hmall").id(item.getId().toString());
            // 2.准备Json文档
            request.source(JSON.toJSONString(itemDoc), XContentType.JSON);
            // 3.发送请求
            client.index(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 下架消息接收
     *
     * @param id
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = MqConstants.HAMLL_DOWN_QUEUE),
            //ExchangeTypes.TOPIC表示Exchange类型，默认是direct
            exchange = @Exchange(name = MqConstants.HMALL_EXCHANGE, type = ExchangeTypes.TOPIC),
            key = MqConstants.HMALL_DOWN_KEY
    ))
    public void downQueue(Long id) {
        System.out.println("消费者downQueue接收到消息：【" + id + "】");
        try {
            // 1.准备Request
            DeleteRequest request = new DeleteRequest("hmall", id.toString());
            // 2.发送请求
            client.delete(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


}